package j20251112;

import java.util.concurrent.CountDownLatch;


public class Demo11 {
    public static void main(String[] args) throws Exception {
        // 10 个线程等待其他线程执行完毕
        CountDownLatch latch = new CountDownLatch(10);
        Runnable r = new Runnable() {
            // 每个线程执行的任务
            @Override
            public void run() {
                try {
                    Thread.sleep((long) (Math.random() * 10000));
                    // 每个线程执行完毕后, 计数器减 1
                    latch.countDown();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        // 10 个线程同时执行任务
        for (int i = 0; i < 10; i++) {
            new Thread(r).start();
            System.out.println("线程" + i + "等待其他线程");
        }
        // 等待所有线程执行完毕, 计数器减到 0 时, 继续执行后续代码
        latch.await();
        System.out.println("所有线程执行完毕");
    }
}
